//
//  PopMeumView.m
//  SinaWeibo
//
//  Created by Apple on 16/8/10.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "PopMeumView.h"

@interface PopMeumView()


@end

@implementation PopMeumView


#pragma mark ---- 封装下拉菜单方法

static UIWindow *myWindow;
static dismissBlock myChangeTitleImage;
static UIViewController *myContentVC;

+(void)popFrom:(UIView *)fromView content:(UIView *)contentView dissmissBlock:(dismissBlock)dismiss{
    
    //是的block生命周期更长
    myChangeTitleImage = [dismiss copy];
    
    //1.创建window
    myWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    myWindow.windowLevel = UIWindowLevelAlert;
    
    [myWindow makeKeyAndVisible];
    
    //2.创建蒙板
    UIButton *coverView = [[UIButton alloc]initWithFrame:[UIScreen mainScreen].bounds];
    coverView.backgroundColor = [UIColor clearColor];
    
    //2.1监听
    [coverView addTarget:self action:@selector(clickCoverView:) forControlEvents:UIControlEventTouchUpInside];
    //2.2将蒙板添加到window
    [myWindow addSubview:coverView];
    
    //3.创建groupView，将group添加到蒙板上
    UIImageView *groupView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"popover_background"]];
    
    //开启imageView的用户交互
    groupView.userInteractionEnabled = YES;
    
    [coverView addSubview:groupView];
    
    //4.将需要显示的View添加到groupView上 ,添加要显示数据View和group的间隙
    CGFloat margin = 15;
    
    contentView.frame = CGRectMake(margin, margin, contentView.frame.size.width, contentView.frame.size.height);
    
    
    [groupView addSubview:contentView];
    
    //5.设置groupView的frame；
    //fromView转换后的frame和中心点
    
    CGRect convertFrame =  [myWindow convertRect:fromView.frame fromView:fromView.superview];
    
    CGPoint convertCenter = [myWindow convertPoint:fromView.center fromView:fromView.superview];
    
    
    [groupView setFrame:CGRectMake( convertFrame.origin.x - groupView.frame.size.width*0.5 + fromView.frame.size.width*0.5, CGRectGetMaxY(convertFrame)-5, CGRectGetMaxX(contentView.frame)+margin, CGRectGetMaxY(contentView.frame)+margin)];
    [groupView setCenter:CGPointMake(convertCenter.x, convertCenter.y + groupView.frame.size.height*0.5 + fromView.frame.size.height*0.5-3)];
    
}


//只需要传入设置要view.size的控制器

+(void)popFrom:(UIView *)fromView contentVC:(UIViewController *)contentVC dissmissBlock:(dismissBlock)dismiss{
    //延长控制器生命周期
    myContentVC = contentVC;
    
    [self popFrom:fromView content:contentVC.view dissmissBlock:dismiss];
    
}

//监听点击蒙板事件
+ (void)clickCoverView:(UIButton *)coverView{
    
    NSLog(@"点击蒙板");
    
    //改变按钮状态
    if (myChangeTitleImage != nil) {
        myChangeTitleImage();
    }

    
    //清空蒙板
    myWindow.hidden = YES;
    myWindow = nil;
}


@end
